package com.scoresystem.web.service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.scoresystem.common.CommonValue;
import com.scoresystem.dao.DaoFactory;
import com.scoresystem.dao.ISubjectDao;
import com.scoresystem.json.JsonContext;
import com.scoresystem.json.JsonState;
import com.scoresystem.model.Subject;
import org.apache.commons.beanutils.BeanUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
 * @author Administrator
 *用于处理课程管理的业务逻辑类
 */
public class SubjectService {
	private DaoFactory factory=DaoFactory.getInstance();
	//维护json的状态类
	private JsonState state=new JsonState();
	//根据不同的json状态选择不同的处理方法
	private JsonContext context=new JsonContext(state);
	
	public JSONObject checkout(){
		ISubjectDao dao=factory.createSubjectDao();
		List<Subject> list=dao.findAll();
		try{
			if(list==null){
				state.setState(CommonValue.STATE_FAILED);
				return context.getObject("数据库异常", null, null);
			}
			else{
				JSONArray jsonArr = JSONArray.fromObject(list);
				state.setState(CommonValue.STATE_SUCCESS);
				return context.getObject("查询成功", null,jsonArr);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return new JSONObject();
	}
	/**
	 * 测试Beanutils用，重构阶段可考虑删去
	 * @param map
	 */
	public void populate(Map map){
		Subject subject=new Subject();
		try {
			Map tmpmap=new HashMap();
			tmpmap.putAll(map);
			if(tmpmap.containsKey("op"))
				tmpmap.remove("op");
			BeanUtils.populate(subject, tmpmap);		
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}		
}
